package com.llsydn.service.remote;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.llsydn.hello.R;

/**
 * @author lilinshen
 * @title 远程服务测试（这个activity应该放在client客户端中）
 * @description 请填写相关描述
 * @date 2018/9/29 11:05
 */
public class RemoteServiceActivity extends AppCompatActivity {
    private EditText et_aidl_id;
    private ServiceConnection connection;
    private IStudentService studentService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_remote_service);

        et_aidl_id = findViewById(R.id.et_aidl_id);
    }

    /**
     * 绑定远程服务
     *
     * @param view
     */
    public void bindRemoteService(View view) {
        Intent intent = new Intent("com.llsydn.service.remote.RemoteService.Action");
        if (connection == null) {
            connection = new ServiceConnection() {
                @Override
                public void onServiceConnected(ComponentName name, IBinder service) {
                    Log.e("TAG", "onServiceConnected()");
                    studentService = IStudentService.Stub.asInterface(service);
                }

                @Override
                public void onServiceDisconnected(ComponentName name) {

                }
            };
            bindService(intent, connection, Context.BIND_AUTO_CREATE);
            Toast.makeText(this, "绑定service", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "已经绑定service", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 调用远程服务方法
     *
     * @param view
     */
    public void invokeRemote(View view) throws RemoteException {
        if (studentService != null) {
            int id = Integer.parseInt(et_aidl_id.getText().toString());
            Student student = studentService.getStudentById(id);
            Toast.makeText(this, student.toString(), Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 解绑远程服务
     *
     * @param view
     */
    public void unbindRemoteService(View view) {
        if (connection != null) {
            unbindService(connection);
            connection = null;
            Toast.makeText(this, "解绑service", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "还未绑定service", Toast.LENGTH_SHORT).show();
        }
    }

}
